package com.ruoyi.workflow.service.impl;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.domain.PageQuery;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.flowable.core.domain.ProcessQuery;
import com.ruoyi.flowable.utils.ProcessUtils;
import com.ruoyi.workflow.domain.WfDeployForm;
import com.ruoyi.workflow.domain.vo.WfDeployVo;
import com.ruoyi.workflow.mapper.WfDeployFormMapper;
import com.ruoyi.workflow.service.IWfDeployService;
import lombok.RequiredArgsConstructor;
import org.flowable.common.engine.impl.db.SuspensionState;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lgy
 * @createTime 2022/6/30 9:04
 */
@RequiredArgsConstructor
@Service
public class WfDeployServiceImpl implements IWfDeployService {

    private final RepositoryService repositoryService;
    private final WfDeployFormMapper deployFormMapper;

    /**
     * 部署列表分页查询
     * 部署与流程定义是对应的：流程定义信息更详细，所以查询流程定义数据
     * 部署多次会存在多个版本
     * 主页面只显示最新版本
     */
    @Override
    public TableDataInfo<WfDeployVo> queryPageList(ProcessQuery processQuery, PageQuery pageQuery) {
        // 流程定义列表数据查询
        ProcessDefinitionQuery query = repositoryService
                .createProcessDefinitionQuery()
                // 最新版本
                .latestVersion()
                // 流程定义没有时间，可以按照定义key排序
                .orderByProcessDefinitionKey()
                .desc();
        // 构建搜索条件
        ProcessUtils.buildProcessSearch(query, processQuery);
        long pageTotal = query.count();
        if (pageTotal <= 0) {
            return TableDataInfo.build();
        } else {
            Page<WfDeployVo> page = new Page<>();
            page.setRecords(buildDeployVoList(pageQuery, query));
            page.setTotal(pageTotal);
            return TableDataInfo.build(page);
        }
    }

    /**
     * 依据流程定义信息，构建部署信息
     * */
    private List<WfDeployVo> buildDeployVoList(PageQuery pageQuery, ProcessDefinitionQuery pdQuery) {
        int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1);
        // 分页查询流程定义
        List<ProcessDefinition> definitionList = pdQuery.listPage(offset, pageQuery.getPageSize());
        List<WfDeployVo> deployVoList = new ArrayList<>(definitionList.size());
        for (ProcessDefinition processDefinition : definitionList) {
            // 查询部署信息
            Deployment deployment = repositoryService
                    .createDeploymentQuery()
                    // 依据部署ID查询
                    .deploymentId(processDefinition.getDeploymentId())
                    .singleResult();
            // 构建部署信息
            WfDeployVo vo = buildDeployVo(processDefinition);
            // 流程分类：构建部署信息已经赋值（部署、流程定义中都包含有流程分类）
            //vo.setCategory(deployment.getCategory());
            // 部署时间
            vo.setDeploymentTime(deployment.getDeploymentTime());
            deployVoList.add(vo);
        }
        return deployVoList;
    }

    @Override
    public TableDataInfo<WfDeployVo> queryPublishList(String processKey, PageQuery pageQuery) {
        // 创建查询条件
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery()
                // 依据流程定义key查询
                .processDefinitionKey(processKey)
                // 版本排序
                .orderByProcessDefinitionVersion()
                // 降序
                .desc();
        long pageTotal = query.count();
        if (pageTotal <= 0) {
            return TableDataInfo.build();
        } else {
            // 根据查询条件，查询所有版本
            int offset = pageQuery.getPageSize() * (pageQuery.getPageNum() - 1);
            List<ProcessDefinition> pdList = query.listPage(offset, pageQuery.getPageSize());
            List<WfDeployVo> dvList = pdList
                    .stream()
                    .map(this::buildDeployVo)
                    .collect(Collectors.toList());
            Page<WfDeployVo> page = new Page<>();
            page.setRecords(dvList);
            page.setTotal(pageTotal);
            return TableDataInfo.build(page);
        }
    }

    /**
     * 构建部署信息：信息来源流程定义
     */
    private WfDeployVo buildDeployVo(ProcessDefinition pd) {
        WfDeployVo vo = new WfDeployVo();
        vo.setDefinitionId(pd.getId());
        vo.setProcessKey(pd.getKey());
        vo.setProcessName(pd.getName());
        vo.setVersion(pd.getVersion());
        vo.setCategory(pd.getCategory());
        vo.setDeploymentId(pd.getDeploymentId());
        vo.setSuspended(pd.isSuspended());
        return vo;
    }

    /**
     * 激活或挂起流程
     *
     * @param state        状态
     * @param definitionId 流程定义ID
     */
    @Override
    public void updateState(String definitionId, String state) {
        if (SuspensionState.ACTIVE.toString().equals(state)) {
            // 激活
            repositoryService.activateProcessDefinitionById(definitionId, true, null);
        } else if (SuspensionState.SUSPENDED.toString().equals(state)) {
            // 挂起
            repositoryService.suspendProcessDefinitionById(definitionId, true, null);
        }
    }

    @Override
    public String queryBpmnXmlById(String definitionId) {
        InputStream inputStream = repositoryService.getProcessModel(definitionId);
        try {
            return IoUtil.readUtf8(inputStream);
        } catch (IORuntimeException exception) {
            throw new RuntimeException("加载xml文件异常");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<String> deployIds) {
        for (String deployId : deployIds) {
            repositoryService.deleteDeployment(deployId, true);
            deployFormMapper.delete(new LambdaQueryWrapper<WfDeployForm>().eq(WfDeployForm::getDeployId, deployId));
        }
    }
}
